import { ChatPanel } from "@/components/ChatPanel";
import { CommandInput } from "@/components/CommandInput";
import { TaskPanel } from "@/components/TaskPanel";
import { cn } from "@/lib/utils";
import type { Task } from "@/types/task";
import { useEffect, useRef, useState } from "react";
import "./App.css";
import { streamChat } from "@/lib/ai";
import { TaskFunctions } from "@/lib/ai";
import { Message } from "./types/message";

// 生成 5 位大写随机字符串
const generateTaskId = (): string => {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  let result = "";
  for (let i = 0; i < 5; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

function App() {
  const containerRef = useRef<HTMLDivElement>(null);
  const [isResizing, setIsResizing] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [theme, setTheme] = useState<"light" | "dark" | "system">(
    () =>
      (localStorage.getItem("theme") as "light" | "dark" | "system") || "system"
  );

  // 从 localStorage 获取宽度，如果没有则计算初始宽度为容器的 1/3
  const [leftWidth, setLeftWidth] = useState(() => {
    const savedWidth = localStorage.getItem("leftPanelWidth");
    if (savedWidth) return parseInt(savedWidth);
    return Math.floor(window.innerWidth / 3);
  });

  // 当宽度改变时保存到 localStorage
  useEffect(() => {
    localStorage.setItem("leftPanelWidth", leftWidth.toString());
  }, [leftWidth]);

  // 初始化主题
  useEffect(() => {
    const root = document.documentElement;
    const savedTheme = localStorage.getItem("theme") as
      | "light"
      | "dark"
      | "system";

    if (savedTheme) {
      if (savedTheme === "system") {
        const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
          .matches
          ? "dark"
          : "light";
        root.classList.toggle("dark", systemTheme === "dark");
      } else {
        root.classList.toggle("dark", savedTheme === "dark");
      }
    }
  }, []);

  // 处理系统主题变化
  useEffect(() => {
    const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");

    const handleChange = () => {
      if (theme === "system") {
        document.documentElement.classList.toggle("dark", mediaQuery.matches);
      }
    };

    handleChange();
    mediaQuery.addEventListener("change", handleChange);

    return () => mediaQuery.removeEventListener("change", handleChange);
  }, [theme]);

  // 处理主题变化
  const handleThemeChange = (newTheme: "light" | "dark" | "system") => {
    setTheme(newTheme);
    localStorage.setItem("theme", newTheme);

    const root = document.documentElement;
    if (newTheme === "system") {
      const systemTheme = window.matchMedia(
        "(prefers-color-scheme: dark)"
      ).matches;
      root.classList.toggle("dark", systemTheme);
    } else {
      root.classList.toggle("dark", newTheme === "dark");
    }
  };

  const handleMouseMove = (e: MouseEvent) => {
    if (!isResizing || !containerRef.current) return;

    const containerRect = containerRef.current.getBoundingClientRect();
    const newWidth = e.clientX - containerRect.left;

    // 限制最小宽度为容器的 1/4，最大宽度为容器的 1/2
    const minWidth = Math.floor(containerRect.width / 4);
    const maxWidth = Math.floor(containerRect.width / 2);
    setLeftWidth(Math.min(Math.max(newWidth, minWidth), maxWidth));
  };

  useEffect(() => {
    if (!isResizing) return;

    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", () => setIsResizing(false));

    return () => {
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", () => setIsResizing(false));
    };
  }, [isResizing]);

  const handleCommand = async (
    content: string,
    mode: "chat" | "task",
    removeEditMessage: boolean = false
  ) => {
    if (mode === "chat") {
      setMessages((messages) => {
        let newMessages = messages;
        if (removeEditMessage) {
          newMessages = messages.slice(0, -2);
        }
        return [...newMessages, { role: "user", content, type: "text" }];
      });

      const tempId = Date.now().toString();
      setMessages((prev) => [
        ...prev,
        { role: "assistant", content: "", id: tempId, type: "text" },
      ]);

      const taskFunctions: TaskFunctions = {
        createTask: handleTasksCreate,
        updateTask: handleTaskUpdate,
        deleteTask: handleTaskDelete,
      };

      let fullResponse = "";
      for await (const chunk of streamChat(content, tasks, taskFunctions)) {
        fullResponse = chunk.content.startsWith("\r")
          ? fullResponse.split("\n")[0] + "\n" + chunk.content.slice(1)
          : fullResponse + chunk.content;

        setMessages((prev) =>
          prev.map((msg) =>
            msg.id === tempId
              ? { ...msg, content: fullResponse, type: chunk.type }
              : msg
          )
        );
      }
    } else {
      // 添加新任务
      const task: Task = {
        id: generateTaskId(),
        title: content,
        type: "task",
        status: "todo",
        createdAt: new Date(),
      };
      setTasks([...tasks, task]);
    }
  };

  const handleTasksCreate = async (tasksData: Partial<Task>) => {
    const newTasks = [
      {
        id: generateTaskId(),
        title: tasksData.title || "",
        type: tasksData.type || "task",
        status: tasksData.status || "todo",
        description: tasksData.description,
        createdAt: new Date(),
      },
    ];
    setTasks((prev) => [...prev, ...newTasks]);
  };

  const handleTaskUpdate = async (taskId: string, updates: Partial<Task>) => {
    setTasks(
      tasks.map((task) => (task.id === taskId ? { ...task, ...updates } : task))
    );
  };

  const handleTaskDelete = async (taskId: string) => {
    setTasks(tasks.filter((task) => task.id !== taskId));
  };

  const handleClearMessages = () => {
    setMessages([]);
  };

  const fetchEditMessage = () => {
    if (messages.length > 1) {
      return messages[messages.length - 2].content;
    }
    return "";
  };

  return (
    <div className="flex flex-col h-screen bg-background">
      <div ref={containerRef} className="flex flex-1 overflow-hidden">
        {/* 左侧聊天面板 */}
        <div
          className={cn("border-r border-border", isResizing && "select-none")}
          style={{ width: leftWidth, minWidth: leftWidth, maxWidth: leftWidth }}
        >
          <ChatPanel messages={messages} onClear={handleClearMessages} />
        </div>

        {/* 拖动分隔条 */}
        <div
          className={cn(
            "w-1 bg-border hover:bg-primary/50 cursor-col-resize transition-colors",
            isResizing && "bg-primary"
          )}
          onMouseDown={() => setIsResizing(true)}
        />

        {/* 右侧任务面板 */}
        <div className="flex-1">
          <TaskPanel
            tasks={tasks}
            onCreate={handleTasksCreate}
            onUpdate={handleTaskUpdate}
            onDelete={handleTaskDelete}
            themeProps={{
              theme,
              setTheme: handleThemeChange,
            }}
          />
        </div>
      </div>

      {/* 命令输入框 */}
      <CommandInput
        onSubmit={handleCommand}
        onClear={handleClearMessages}
        fetchEditMessage={fetchEditMessage}
      />
    </div>
  );
}

export default App;
